package com.cskaoyan.service.admin;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.admin.RoleExample;
import com.cskaoyan.bean.admin.Role;
import com.cskaoyan.bean.admin.vo.RoleOptionsVo;
import com.cskaoyan.mapper.admin.RoleMapper;
import com.cskaoyan.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 类<code>Doc</code>用于：TODO
 *
 * @author Acher
 * @version 1.0
 * @date 2021-10-18
 */
@Service
public class RoleServiceImpl implements RoleService{

    @Autowired
    RoleMapper roleMapper;

    @Override
    public PageDataVo options() {
        List<Role> roleList = roleMapper.selectByExample(new RoleExample());
        List<RoleOptionsVo> roleOptionsVoList = new ArrayList<>();
        for (Role role : roleList) {
            RoleOptionsVo roleOptionsVo = new RoleOptionsVo();
            roleOptionsVo.setValue(role.getId());
            roleOptionsVo.setLabel(role.getName());
            roleOptionsVoList.add(roleOptionsVo);
        }
        return PageDataVo.ok(roleOptionsVoList);
    }

    @Override
    public PageDataVo query(String name, BaseParam param) {
        //配置分页信息 → 在执行预编译过程，会帮你拼接分页的sql语句
        PageHelper.startPage(param.getPage(), param.getLimit());
        RoleExample example = new RoleExample();
        //构造条件 → List<Criterion> → and方法做的事情就是构造一个Criterion的对象添加到List里
        //如果username不为null，拼接条件 and username like '%songge%'
        RoleExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(name))
            criteria.andNameLike("%" + name + "%");
        criteria.andDeletedEqualTo(false);
        //设置排序
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<Role> roleList = roleMapper.selectByExample(example);
        //分页插件 → 做分页
        //执行完查询之后，可以获得分页结果 → 用哪些数据取决于你的前端需要哪些数据
        //PageInfo中需要传入查询结果
        return PageDataVo.ok(roleList);
    }

    @Override
    public boolean update(Role role) {
        RoleExample example = new RoleExample();
        example.createCriteria().andNameEqualTo(role.getName());
        return roleMapper.updateByExampleSelective(role, example) == 1;
    }

    @Override
    public boolean delete(Role role) {
        RoleExample example = new RoleExample();
        example.createCriteria().andNameEqualTo(role.getName());
        return roleMapper.deleteByExample(example) == 1;
    }

    @Override
    public boolean create(Role role) {
        return roleMapper.insert(role) == 1;
    }
}
